package com.sh.apibackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sh.apibackend.annotation.AuthCheck;
import com.sh.apibackend.common.BaseResponse;
import com.sh.apibackend.common.ErrorCode;
import com.sh.apibackend.common.ResultUtils;
import com.sh.apibackend.exception.BusinessException;
import com.sh.apibackend.model.userinterface.UpdateUserInterfaceInfoDTO;
import com.sh.apibackend.model.userinterface.UserInterfaceInfoAddRequest;
import com.sh.apibackend.model.vo.UserInterfaceInfoVO;
import com.sh.apibackend.service.InterfaceChargingService;
import com.sh.apibackend.service.InterfaceInfoService;
import com.sh.apibackend.service.UserInterfaceInfoService;
import com.sh.apibackend.service.UserService;
import com.sh.apicommon.entity.InterfaceCharging;
import com.sh.apicommon.entity.User;
import com.sh.apicommon.entity.UserInterfaceInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户与接口相关
 *
 * @author sh
 */
@RestController
@Slf4j
@RequestMapping("apibackend/userInterfaceInfo")
public class UserInterfaceInfoController {

    @Resource
    private UserService userService;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Resource
    private InterfaceChargingService interfaceChargingService;


    /**
     * 根据id查找接口
     */
    @GetMapping("/list/userId")
    public BaseResponse<List<UserInterfaceInfoVO>> getInterfaceInfoByUserId(@RequestParam Long userId, HttpServletRequest request){
        List<UserInterfaceInfoVO > userInterfaceInfoVOList = userInterfaceInfoService.getInterfaceInfoByUserId(userId, request);
        return ResultUtils.success(userInterfaceInfoVOList);
    }



    /**
     * 创建
     * @param userInterfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Long> addUserInterfaceInfo(@RequestBody UserInterfaceInfoAddRequest userInterfaceInfoAddRequest, HttpServletRequest request) {
        if (userInterfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        return null;
    }

    /**
     * 免费的接口获取免费次数
     */
    @PostMapping("/getFreeNum")
    public BaseResponse<Boolean> getFreeInterfaceCount(@RequestBody UpdateUserInterfaceInfoDTO updateUserInterfaceInfoDTO, HttpServletRequest request){
        Long interfaceId = updateUserInterfaceInfoDTO.getInterfaceId();  // 获取接口id
        Long userId = updateUserInterfaceInfoDTO.getUserId();  // 获取用户id
        Long lockNum = updateUserInterfaceInfoDTO.getLockNum();  // 获取要激活的次数
        if ( interfaceId ==null || userId == null || lockNum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if ( lockNum>100){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "一次性最多只能激活100个");
        }
        synchronized (userId){
            User loginUser = userService.getLoginUser(request);
            if ( !userId.equals(loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 看看付费表里有没有这个接口
            QueryWrapper<InterfaceCharging> queryWrapper = new QueryWrapper<InterfaceCharging>().eq("interfaceId", interfaceId);
            long count = interfaceChargingService.count(queryWrapper);
            if (count>0){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "该接口为收费接口");
            }
            // 用户接口关系表里面有没有这条数据
            QueryWrapper<UserInterfaceInfo> eq = new QueryWrapper<UserInterfaceInfo>().eq("userId", userId).eq("interfaceInfoId", interfaceId);
            UserInterfaceInfo one = userInterfaceInfoService.getOne(eq);

            if(  one!=null && one.getLeftNum()>1000 ){  // 用户已经激活了1000次
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "您的剩余次数已达上限");
            }
            // 激活次数
            boolean b = userInterfaceInfoService.updateUserInterfaceInfo(updateUserInterfaceInfoDTO);
            return ResultUtils.success(b);
        }
    }

}
